<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="退货审核"
    @ok="handleSubmit"
    @visible-change="handleVisibleChange"
  >
    <BasicForm @register="registerForm" :model="model" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { approveRefund, rejectRefund } from '/@/api/sys/refundOrder';
  import { formSchema } from './refundData';
  import { AxiosResponse } from 'axios';

  export default defineComponent({
    name: 'RefundModal',
    components: { BasicModal, BasicForm },
    props: {
      order: { type: Object },
    },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const isUpdate = ref(true);
      const modelRef = ref({});

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();

        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          console.log({ ...data.order });

          setFieldsValue({
            ...data.order,
          });
          console.log(modelRef);
        }
      });

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api
          if (values.status === 0) {
            if (values.unionOrderid === '') {
            }
            await approveRefund(values).then((resp: AxiosResponse<any>) => {
              console.log(resp);
            });
          } else {
            await rejectRefund(values).then((resp: AxiosResponse<any>) => {
              console.log(resp);
            });
          }
          console.log(values);
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      function onDataReceive(data) {
        console.log('Data Received', data);
      }

      function handleVisibleChange(v, b) {
        console.log(b);

        v && props.order && nextTick(() => onDataReceive(props.order));
      }

      return { registerForm, registerModal, handleSubmit, model: modelRef, handleVisibleChange };
    },
  });
</script>
